<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      width="38%"
      :visible="showDialog"
      @close="close"
    >
      <el-form
        label-width="120px"
        :model="formData"
        :rules="rules"
        ref="formData"
      >
        <el-form-item label="农产品名称" prop="name">
          <el-input
            style="width: 80%"
            placeholder="请输入农产品名称"
            v-model="formData.name"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="农产品类别" prop="categoryId">
          <el-select
            v-model="formData.categoryId"
            placeholder="请选择农产品类别"
          >
            <!-- label表示显示内容 value表示选项的值 -->
            <el-option
              v-for="item in categoriesData"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="农产品图片" prop="imageUrl">
          <el-upload
            name="image"
            class="avatar-uploader"
            :action="imageAction.url"
            :headers="imageAction.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="formData.imageUrl"
              :src="formData.imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input
            type="textarea"
            :rows="2"
            style="width: 80%"
            placeholder="2-100个字符"
            v-model="formData.description"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input
            style="width: 80%"
            placeholder="请输入价格"
            v-model="formData.price"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input
            style="width: 80%"
            placeholder="请输入单位"
            v-model="formData.unit"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="stock">
          <el-input
            style="width: 80%"
            placeholder="请输入数量"
            v-model="formData.stock"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="15">
              <el-button type="primary" @click="btnConfirm('formData')"
                >确定</el-button
              >
              <el-button @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  addProduct,
  selectProductById,
  validateProductName,
  updateProductById,
} from "@/api/product";
import { getToken } from "@/utils/auth";
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    categoriesData: {
      type: Array,
      default: [],
    },
    productId: {
      type: Number,
      default: null,
    },
    dialogTitle: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      // 上传图片对象
      imageAction: {
        url: "/api/upload",
        headers: {
          token: getToken(),
        },
      },
      formData: {
        name: "",
        description: "",
        price: "",
        stock: "",
        imageUrl: "",
        unit: "",
        categoryId: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "农产品名称不能为空",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: async (rule, value, callback) => {
              const result = await validateProductName(this.formData.name);
              if (result) {
                callback(new Error(result));
              } else {
                callback();
              }
            },
          },
        ],
        description: [
          {
            required: true,
            message: "农产品介绍不能为空",
            trigger: "blur",
          },
          {
            min: 2,
            max: 100,
            message: "描述信息长度为2-100个字符",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: "农产品价格不能为空",
            trigger: "blur",
          },
        ],
        stock: [
          {
            required: true,
            message: "农产品数量不能为空",
            trigger: "blur",
          },
        ],
        imageUrl: [
          {
            required: false,
            message: "农产品图片不能为空",
            trigger: "blur",
          },
        ],
        unit: [
          {
            required: true,
            message: "单位不能为空",
            trigger: "blur",
          },
        ],
        categoryId: [
          {
            required: true,
            message: "农产品类别不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 关闭
    close() {
      this.$refs.formData.resetFields();
      this.$emit("update:showDialog", false);
    },
    // 确认
    btnConfirm() {
      if (this.dialogTitle === "新增农产品") {
        this.$refs.formData.validate(async (isOk) => {
          if (isOk) {
            this.addProductMsg();
          }
        });
      } else if (this.dialogTitle === "编辑农产品") {
        this.$refs.formData.validate(async (isOk) => {
          if (isOk) {
            this.updateProductMsg();
          }
        });
      }
    },
    // 图片上传成功后回调
    handleAvatarSuccess(res) {
      this.formData.imageUrl = res.data;
    },
    // 编辑 数据回写
    async editProduct(id) {
      await selectProductById(id).then((res) => {
        this.formData = res;
      });
    },
    // 添加弹窗
    async addProductMsg() {
      await addProduct(this.formData).then((res) => {
        this.$emit("addProductSuccess");
        this.$message.success("新增农产品成功");
        this.close();
      });
    },
    // 更新弹窗
    async updateProductMsg() {
      await updateProductById({ ...this.formData, id: this.productId }).then(
        (res) => {
          this.$emit("addProductSuccess");
          this.$message.success("修改农产品成功");
          this.close();
        }
      );
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>